/** 封装网络请求 */
const baseUrl = '/api/admin';
/** token */
const token = sessionStorage.getItem("token");
let headers = {
    'Content-Type': 'application/json;charset=UTF-8'
};
if (token) {
    headers["Authorization"] = token;
}

/** 显示加载动画 */
function showLoading(isLoading) {
    if (isLoading) {
        layer.load(1);
    }
}

/** 关闭加载动画 */
function hideLoading(isLoading) {
    if (isLoading) {
        layer.closeAll('loading');
    }
}

/** 处理响应 */
function handleResponse(res, resolve, reject) {
    hideLoading(true);
    const resp=res
    switch (res.code) {
        case 200:
            resolve(resp);
            break;
        case 400:
            layer.msg(resp.message, {icon: 7});
            reject(resp.data);
            break;
        case 401:
            layer.msg('登录过期，请重新登录', {icon: 7});
            setTimeout(() => {
                sessionStorage.clear();
                window.location.href = '/page/login.html';
            }, 1500);
            break;
        case 403:
            layer.msg('您无权限访问此系统', {icon: 7});
            setTimeout(() => {
                sessionStorage.clear();
                window.location.href = '/page/login.html';
            }, 1500);
            break;
        default:
            layer.msg(resp.message || '请求失败', {icon: 7});
            reject(resp.data);
            break;
    }
}

/** 处理错误 */
function handleError(err, reject) {
    layer.msg(err.responseText || '请求错误', {icon: 7});
    reject(err);
}

/** 发送请求 */
function request(url = '', method = 'GET', params = {}, isLoading = false) {
    showLoading(isLoading);

    // 验证method参数
    method = method.toUpperCase();


    // 将params转为JSON字符串
    let data = method === 'POST'? JSON.stringify(params) : params;

    return new Promise((resolve, reject) => {
        $.ajax({
            url: `${baseUrl}${url}`,
            cache: false,
            datatype: 'json',
            type: method,
            data: data,
            headers,
            success: res => handleResponse(res, resolve, reject),
            error: err => handleError(err, reject)
        });
    });
}

function getData(url = '', params = {}, isLoading = false) {
    return request(url, 'GET', params, isLoading);
}

function postData(url = '', params = {}, isLoading = false) {
    return request(url, 'POST', params, isLoading);
}
